//package com.thread.threadfirst.marvel.citymaster.service;
//
//import com.fugui.marvel.common.enums.TUserRebateHistoryTypeEnum;
//import com.fugui.marvel.common.utils.StringUtils;
//import com.fugui.marvel.service.citymaster.annotation.Log;
//import com.fugui.marvel.service.citymaster.annotation.LogTypeEnum;
//import com.fugui.marvel.service.citymaster.conf.RedisKeyGeneratorConfig;
//import com.fugui.marvel.service.citymaster.entity.Query;
//import com.fugui.marvel.service.citymaster.enums.ApplyCityType;
//import com.fugui.marvel.service.citymaster.enums.IncomeStatus;
//import com.fugui.marvel.service.citymaster.mapper.ApplyCityMasterMapper;
//import com.fugui.marvel.service.citymaster.mapper.CityConfigMapper;
//import com.fugui.marvel.service.citymaster.mapper.IncomeDetailsMapper;
//import com.fugui.marvel.service.common.domain.user.TUser;
//import com.fugui.marvel.service.common.dto.ReturnT;
//import com.fugui.marvel.service.common.dto.citymaster.*;
//import com.fugui.marvel.service.common.service.feign.client.citymaster.FeignIncomeDetailsServiceClient;
//import com.fugui.marvel.service.common.service.feign.client.user.FeignUserAccountServiceClient;
//import com.fugui.marvel.service.common.service.feign.client.user.FeignUserServiceClient;
//import io.swagger.annotations.Api;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Comparator;
//import java.util.List;
//import java.util.Optional;
//import java.util.concurrent.atomic.AtomicInteger;
//import java.util.stream.Collectors;
//
//import static com.fugui.marvel.common.utils.UUIDGenerator.getUUID;
//
///**
// * @author yinwensheng
// * @date
// */
//@Api("收益明细Service")
//@Service
//@RestController
//@Transactional(rollbackFor = Exception.class)
//public class IncomeDetailsServiceImpl implements FeignIncomeDetailsServiceClient {
//
//
//    /**
//     *
//     */
//    private static final Logger log = LoggerFactory.getLogger(ApplyCityMasterServiceImpl.class);
//
//
//    /**
//     *
//     */
//    @Autowired
//    FeignUserServiceClient feignUserServiceClient;
//
//    /**
//     *
//     */
//    @Autowired
//    FeignUserAccountServiceClient feignUserAccountServiceClient;
//
//    /**
//     *
//     */
//    @Autowired
//    RedisService feignRedisServiceClient;
//    /**
//     *
//     */
//    @Autowired
//    CityConfigMapper cityConfigMapper;
//
//
//    /**
//     *
//     */
//    @Autowired
//    ApplyCityMasterMapper applyCityMasterMapper;
//
//
//    /**
//     *
//     */
//    @Autowired
//    IncomeDetailsMapper incomeDetailsMapper;
//
//
//    /**
//     *
//     */
//    @Autowired
//    RedisKeyGeneratorConfig redisKeyGeneratorConfig;
//
//
//
//    /**
//     *排行榜
//     * @return
//     */
//    @Log(prefix = "排行榜", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getRanking", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Override
//    public ReturnT<CityMasterRankingDTO> getRanking(@RequestParam(value = "userId") Long userId, @RequestParam(value = "brandId") Long brandId) {
//        ReturnT<CityMasterRankingDTO> returnT = new ReturnT<>();
//
//        try {
//
//            //查询所有当选下台的城主用户
//            List<CityMasterList> userRank = new ArrayList<>();
//            CityMasterRankingDTO result = new CityMasterRankingDTO();
//            List<ApplyCityMasterDTO> userIds = applyCityMasterMapper.getCityMasterByStatus();
//            userIds.stream().forEach((x) -> {
//                CityMasterList item = new CityMasterList();
//                TUser tUser = feignUserServiceClient.getUserID(x.getUserId());
//                if (tUser != null) {
//                    item.setUserId(x.getUserId());
//                    item.setFullName(tUser.getFullname() != null ? tUser.getFullname() : null);
//                    item.setHeaderUrl(tUser.getUserHeadUrl() != null ? tUser.getUserHeadUrl() : null);
//                    item.setBrandId(tUser.getBrandId());
//                }
//                Query query = new Query();
//                query.put("userId",x.getUserId());
//                query.put("brandId",x.getBrandId());
//                BigDecimal bigDecimal = incomeDetailsMapper.getIncomeTotalPriceByUserId(query);
//                if (bigDecimal != null) {
//                    item.setTotalPrice(bigDecimal);
//                } else {
//                    item.setTotalPrice(BigDecimal.ZERO);
//                }
//                userRank.add(item);
//            });
//
//
//            //所有排名
//            List<CityMasterList> allRank = userRank.stream().sorted(Comparator.comparing(CityMasterList::getTotalPrice).reversed()).collect(Collectors.toList());
//            if (allRank != null) {
//                AtomicInteger paiMing = new AtomicInteger(1);
//                allRank.stream().map((x) -> {
//                    x.setRanking(paiMing.getAndIncrement());
//                    return x;
//                }).collect(Collectors.toList());
//            }
//
//
//            //排名前10
//            List<CityMasterList> rank10 = allRank.stream().limit(10).collect(Collectors.toList());
//            result.setRank(rank10);
//
//            //当前用户排名
//            List<CityMasterList> isExit= allRank.stream().filter((x) -> userId.equals(x.getUserId())  && brandId.equals(x.getBrandId())).collect(Collectors.toList());
//            if (isExit!=null  && isExit.size()>0) {
//                result.setIsRanking(true);
//                CityMasterList rank = isExit.get(0);
//                result.setCurrentRanking(rank.getRanking());
//            }
//            returnT.returnSuccess(result);
//        } catch (Exception e) {
//            log.error("getRanking ---------error", e);
//            throw new RuntimeException(e.getMessage());
//        }
//        return returnT;
//    }
//
//
//    /**
//     *
//     * @return
//     */
//    @Log(prefix = "城主提现或者信用卡办理分润处理接口", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getCityTotalIncome", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    public IncomeDetailsDTO getCityTotalIncome( @RequestParam(value = "cityId") Integer cityId) {
//        try {
//
//            Query query = new Query();
//            query.put("cityId",cityId);
//            IncomeDetailsDTO incomeDetailsDTO = incomeDetailsMapper.getCityTotalIncome(query);
//            return incomeDetailsDTO;
//
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
//    }
//
//
//    /**
//     *收益金额
//     * @return
//     */
//    @Log(prefix = "收益金额", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getIncomePriceByUserId", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Override
//    public BigDecimal getIncomePriceByUserId(@RequestParam(value = "userId") Long userId, @RequestParam(value = "date",required=false) String date) {
//        try {
//            Query query = new Query();
//            query.put("userId", userId);
//            if (!StringUtils.isEmpty(date)) {
//                query.put("currentTime", date);
//            }
//            String price = incomeDetailsMapper.getIncomePriceByUserId(query);
//            if (!StringUtils.isEmpty(price)) {
//                return new BigDecimal(price);
//            }
//            return BigDecimal.ZERO;
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
//    }
//
//
//
//
//    /**
//     *
//     * @return
//     */
//    @Log(prefix = "查询当前用户收益记录", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getCityIncomeDetailRecordByCurrentUserId", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Override
//    public ReturnT<List<IncomeDetailsDTO>> getCityIncomeDetailRecordByCurrentUserId(@RequestParam(value = "userId") Long userId) {
//        ReturnT<List<IncomeDetailsDTO>> returnT = new ReturnT<>();
//        try {
//            Query query = new Query();
//            query.put("userId", userId);
//            List<IncomeDetailsDTO> list = incomeDetailsMapper.getCityIncomeDetailRecordByCurrentUserId(query);
//            list.stream().map((x) -> {
//                //查询申请人用户手机号码
//                Optional<TUser> tUser = Optional.ofNullable(feignUserServiceClient.getUserID(x.getApplicationUserId()));
//                if (tUser.isPresent()) {
//                    x.setApplyMobile(tUser.get().getPhone());
//                }
//                return x;
//            }).collect(Collectors.toList());
//            returnT.returnSuccess(list);
//            return returnT;
//
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
//    }
//
//
//    /**
//     *
//     * 获取用户收益详情
//     * @return
//     */
//    @Log(prefix = "获取用户收益详情", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getIncomeDetailById", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Override
//    public ReturnT<IncomeDetailsDTO> getIncomeDetailById(@RequestParam(value = "id") Long id) {
//        ReturnT<IncomeDetailsDTO> returnT = new ReturnT<>();
//        try {
//            IncomeDetailsDTO incomeDetailsDTO = incomeDetailsMapper.getObjectById(id);
//            returnT.returnSuccess(incomeDetailsDTO);
//            return returnT;
//
//        } catch (Exception e) {
//            throw new RuntimeException(e.getMessage());
//        }
//    }
//
//
//
//    /**
//     * 城主提现或者信用卡办理分润处理接口 --Eureka注册对外api
//     *
//     * @param cityId 城市id
//     *               渠道  1 信用卡申请 2 提现
//     */
//    @Log(prefix = "城主提现或者信用卡办理分润处理接口", value = LogTypeEnum.ALL)
//    @Transactional(rollbackFor = Exception.class)
//    @RequestMapping(method = RequestMethod.POST, value = "/m2.0/citymaster/query/isncomeDetails/getCityMasterSplitting", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @Override
//    public BigDecimal getCityMasterSplitting(@RequestParam(value = "applyUserId") Long applyUserId, @RequestParam(value = "cityId") Integer cityId, @RequestParam(value = "applyPrice") BigDecimal applyPrice, @RequestParam(value = "channel") Integer channel) {
//        log.info("城主分润开始applyUserId {} cityId {} applyPrice {} channel{}",applyUserId,cityId,applyPrice,channel);
//        List<BigDecimal> bigDecimals = new ArrayList<>();
//        try {
//            Query queryConfig = new Query();
//            queryConfig.put("cityId", cityId);
//            queryConfig.put("cityStatus", 2);
//            Optional<CityConfigDTO> cityConfigDTO = Optional.ofNullable(cityConfigMapper.getCityByCityIdAndCityStatus(queryConfig));
//            if (cityConfigDTO.isPresent()) {
//                //发起方提现applyUserId applyPrice  --》》 获取发起方用户城市 --》》或者城市城主和副城主2--》》城主（副）扣除金额 -- 》》结束
//                Query query = new Query();
//                query.put("cityId", cityConfigDTO.get().getId());
//                query.put("applyStatus", 2);
//                //查询城市的城主和副城主 userId
//                Optional<List<ApplyCityMasterDTO>> list = Optional.ofNullable(applyCityMasterMapper.getCityMasterAndDeputy(query));
//                if (list.isPresent()) {
//                    list.get().stream().forEach((x) -> {
//                        saveIncomeDetail(bigDecimals, applyUserId, applyPrice, channel, x);
//
//                    });
//                } else {
//                    log.info("》》》》》》》》》》》》》这个城市没有城主 是无法分润的 ");
//                    return applyPrice;
//                }
//                //分润金额
//                BigDecimal total = bigDecimals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
//                BigDecimal finalPrice = applyPrice.subtract(total).setScale(2, BigDecimal.ROUND_UP);
//                return finalPrice;
//
//            } else {
//                log.info("》》》》》》》》》》》》》城主未配置 is null");
//               return applyPrice;
//
//            }
//
//        } catch (Exception e) {
//            throw new RuntimeException("》》》》》》》》》》》》》城主提现或者信用卡办理分润Exception" + e.getMessage());
//        }
//
//    }
//
//
//
////    /**
////     *
////     * @param applyUserId
////     * @param applyPrice
////     * @param channel
////     * @param x
////     */
////    private void saveIncomeDetail(List<BigDecimal> bigDecimals,@RequestParam(value = "applyUserId") long applyUserId, BigDecimal  applyPrice, @RequestParam(value = "channel") Integer channel, ApplyCityMasterDTO x) {
////        feignRedisServiceClient.del(redisKeyGeneratorConfig.getCityMasterIncomeKey(x.getCityId(), x.getUserId(), x.getCityType()));
////        Query save = new Query();
////        BigDecimal finalPrice = BigDecimal.ZERO;
////        String orderId=getUUID();
////        save.put("applicationUserId", applyUserId);
////        save.put("orderId", orderId);
////        save.put("userId", x.getUserId());
////        save.put("cityId", x.getCityId());
////        save.put("cityType", x.getCityType());
////        save.put("channel", channel);
////        save.put("applyStatus", IncomeStatus.IS1.getValue());
////        save.put("mobile", x.getMobile());
////        save.put("brandId", x.getBrandId());
////        save.put("originPrice", applyPrice);
////        if (channel.equals(1)) {
////            BigDecimal bigDecimal = new BigDecimal(5);
////            finalPrice = bigDecimal;
////            if (x.getCityType().equals(ApplyCityType.CT1.getValue()) && applyPrice.compareTo(bigDecimal) > 0) {
////                save.put("deductionRatio", "5%");
////                save.put("actualDeductionPrice", finalPrice);
////                bigDecimals.add(finalPrice);
////                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("finalPrice", price);
////                incomeDetailsMapper.save(save);
////            }
////        } else if (channel.equals(2)) {
////            if (x.getCityType().equals(ApplyCityType.CT1.getValue())) {
////                save.put("deductionRatio", "3%");
////                finalPrice = applyPrice.multiply(new BigDecimal("0.03")).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("actualDeductionPrice", finalPrice);
////                bigDecimals.add(finalPrice);
////                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("finalPrice", price);
////                incomeDetailsMapper.save(save);
////            } else { //副城主1 副城主2
////                save.put("deductionRatio", "1%");
////                finalPrice = applyPrice.multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("actualDeductionPrice", finalPrice);
////                bigDecimals.add(finalPrice);
////                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("finalPrice", price);
////                incomeDetailsMapper.save(save);
////            }
////        }
////        //调用用户账户更新金额接口 涉及到跨库事务问题 TODO  finalPrice
////        if(finalPrice.compareTo(BigDecimal.ZERO) > 0) {
////            String remark="";
////            String mobile="";
////            if (!StringUtils.isEmpty(x.getMobile())){
////                remark = "来自" + x.getMobile().substring(0, 3) + "****" + x.getMobile().substring(x.getMobile().length() - 4, x.getMobile().length());
////                mobile=x.getMobile();
////            }
////            feignUserAccountServiceClient.userProfitadd(x.getUserId(), TUserRebateHistoryTypeEnum.CITYMASTER_REWORD.getKey(),"0",finalPrice.toString(),orderId,remark,mobile,x.getUserId());
////
////        } else {
////            log.info("城主分润金额为0 orderId={}", orderId);
////        }
////    }
////
//
//
//    /**
//     *
//     * @param applyUserId
//     * @param applyPrice
//     * @param channel
//     * @param x
//     */
//    private void saveIncomeDetail(List<BigDecimal> bigDecimals, @RequestParam(value = "applyUserId") long applyUserId, BigDecimal  applyPrice, @RequestParam(value = "channel") Integer channel, ApplyCityMasterDTO x) {
//        feignRedisServiceClient.del(redisKeyGeneratorConfig.getCityMasterIncomeKey(x.getCityId(), x.getUserId(), x.getCityType()));
//        Query save = new Query();
//        BigDecimal finalPrice = BigDecimal.ZERO;
//        String orderId=getUUID();
//        save.put("applicationUserId", applyUserId);
//        save.put("orderId", orderId);
//        save.put("userId", x.getUserId());
//        save.put("cityId", x.getCityId());
//        save.put("cityType", x.getCityType());
//        save.put("channel", channel);
//        save.put("applyStatus", IncomeStatus.IS1.getValue());
//        save.put("mobile", x.getMobile());
//        save.put("brandId", x.getBrandId());
//        save.put("originPrice", applyPrice);
//        if (channel.equals(1)) {
//            BigDecimal bigDecimal = new BigDecimal(5);
//            finalPrice = bigDecimal;
//            if (x.getCityType().equals(ApplyCityType.CT1.getValue()) && applyPrice.compareTo(bigDecimal) > 0) {
//                save.put("deductionRatio", "5%");
//                save.put("actualDeductionPrice", finalPrice);
//                bigDecimals.add(finalPrice);
//                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
//                save.put("finalPrice", price);
//                incomeDetailsMapper.save(save);
//            }
//        } else if (channel.equals(2)) {
////            if (x.getCityType().equals(ApplyCityType.CT1.getValue())) {
////                save.put("deductionRatio", "3%");
////                finalPrice = applyPrice.multiply(new BigDecimal("0.03")).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("actualDeductionPrice", finalPrice);
////                bigDecimals.add(finalPrice);
////                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("finalPrice", price);
////                incomeDetailsMapper.save(save);
////            } else { //副城主1 副城主2
////                save.put("deductionRatio", "1%");
////                finalPrice = applyPrice.multiply(new BigDecimal("0.01")).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("actualDeductionPrice", finalPrice);
////                bigDecimals.add(finalPrice);
////                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
////                save.put("finalPrice", price);
////                incomeDetailsMapper.save(save);
////            }
//        }else if (channel.equals(3)) {
//            if (x.getCityType().equals(ApplyCityType.CT1.getValue())) {
//                save.put("deductionRatio", "15%");
//                finalPrice = applyPrice.multiply(new BigDecimal("0.15")).setScale(2, BigDecimal.ROUND_DOWN);
//                save.put("actualDeductionPrice", finalPrice);
//                bigDecimals.add(finalPrice);
//                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
//                save.put("finalPrice", price);
//                incomeDetailsMapper.save(save);
//            } else { //副城主1 副城主2
//                save.put("deductionRatio", "5%");
//                finalPrice = applyPrice.multiply(new BigDecimal("0.05")).setScale(2, BigDecimal.ROUND_DOWN);
//                save.put("actualDeductionPrice", finalPrice);
//                bigDecimals.add(finalPrice);
//                BigDecimal price = applyPrice.subtract(finalPrice).setScale(2, BigDecimal.ROUND_DOWN);
//                save.put("finalPrice", price);
//                incomeDetailsMapper.save(save);
//            }
//        }
//        //调用用户账户更新金额接口 涉及到跨库事务问题 TODO  finalPrice
//        if(finalPrice.compareTo(BigDecimal.ZERO) > 0) {
//            String remark="";
//            String mobile="";
//            if (!StringUtils.isEmpty(x.getMobile())){
//                 remark = "来自" + x.getMobile().substring(0, 3) + "****" + x.getMobile().substring(x.getMobile().length() - 4, x.getMobile().length());
//                 mobile=x.getMobile();
//            }
//            feignUserAccountServiceClient.userProfitadd(x.getUserId(), TUserRebateHistoryTypeEnum.CITYMASTER_REWORD.getKey(),"0",finalPrice.toString(),orderId,remark,mobile,x.getUserId());
//
//        } else {
//            log.info("城主分润金额为0 orderId={}", orderId);
//        }
//    }
//
//
//}
